from camera_thread import CameraThread
import cv2
from PyQt5.QtGui import QImage
from PyQt5.QtCore import  pyqtSlot
from PyQt5 import QtGui


class BinaryCameraThread(CameraThread):
    """
        继承自摄像头线程类
        在父类的基础上增加了转换，调试二值图的功能
    """
    def __init__(self, camera):
        super(BinaryCameraThread, self).__init__(camera=camera)
        self.threshold_binary = 0
        self.bitwise_not = False

        self.color_table = []
        for i in range(256):
            self.color_table.append(QtGui.qRgb(i, i, i))

    def process_image(self, frame):
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        _, frame = cv2.threshold(frame, self.threshold_binary, 255, cv2.THRESH_BINARY)
        if self.bitwise_not:
            frame = cv2.bitwise_not(frame)   # 黑白翻转
        return frame

    def send_image_to_gui(self, frame):
        h, w = frame.shape
        convertToQtFormat = QImage(frame.data, w, h, QImage.Format_Indexed8)
        convertToQtFormat.setColorTable(self.color_table)
        self.changePixmap.emit(convertToQtFormat)

    @pyqtSlot(int)
    def update_binary(self, threshold_binary):
        self.threshold_binary = threshold_binary

    @pyqtSlot(bool)
    def update_bitwise_not(self, bitwise_not):
        self.bitwise_not = bitwise_not

